// OpenService: cross-platform open with single-open lock
const { shell } = require('electron')
const { spawn } = require('child_process')
const fs = require('fs')

class OpenService {
  constructor() {
    this.isOpening = false
  }

  async open(targetPath, type) {
    if (!targetPath || typeof targetPath !== 'string') {
      return { success: false, message: '目标路径无效' }
    }
    if (this.isOpening) {
      return { success: false, message: '正在打开中，请稍后重试' }
    }
    try {
      if (!fs.existsSync(targetPath)) {
        return { success: false, message: '目标路径不存在' }
      }
      this.isOpening = true
      const res = await shell.openPath(targetPath)
      if (res) {
        // shell.openPath returns empty string on success; otherwise error string
        // fallback per platform
        await this.fallbackOpen(targetPath)
      }
      return { success: true, message: '已打开目标' }
    } catch (err) {
      return { success: false, message: `启动失败: ${err.message}` }
    } finally {
      this.isOpening = false
    }
  }

  fallbackOpen(p) {
    return new Promise((resolve) => {
      let cmd, args
      const platform = process.platform
      if (platform === 'win32') {
        cmd = 'cmd'
        args = ['/c', 'start', '', p]
      } else if (platform === 'darwin') {
        cmd = 'open'
        args = [p]
      } else {
        cmd = 'xdg-open'
        args = [p]
      }
      const child = spawn(cmd, args, { detached: true, stdio: 'ignore' })
      child.on('error', () => resolve())
      child.unref()
      // No reliable completion event; resolve immediately
      resolve()
    })
  }
}

module.exports = { OpenService }
